<template>
	<s-layout title="新建监测任务">
		<view class="cicon-notice"
		      style="padding: 10px;
	          margin: 5px;
	          width: 90%;
	          background-color: #F39800;
	          border-radius: 10px; color: #FFFFFF;">
			<text>任务名称就是关键词翻译一下的英文或中文即可.</text>
		</view>
		<uni-forms
				ref="addressFormRef"
				v-model="state.model"
				:labelStyle="{ fontWeight: 'bold' }"
				border
				labelAlign="left"
				labelWidth="160"
				validateTrigger="bind"
		>
			<view class="bg-white form-box ss-p-x-30">
				<scroll-view
						class="model-content"
						scroll-y
						:scroll-with-animation="true"
				>
					<view class="base-card">
						<uni-forms-item class="form-item" label="任务名称" name="name">
							<uni-easyinput
									v-model="state.model.name"
									:inputBorder="false"
									placeholder="监测关键词英文或中文的译文"
									placeholderStyle="color:#BBBBBB;line-height:normal"
							>
							</uni-easyinput>
						</uni-forms-item>

						<uni-forms-item class="form-item" label="监测词条" name="keyword">
							<uni-easyinput
									v-model="state.model.taskKeyword.keyword"
									:inputBorder="false"
									placeholder="煤炉搜索日文关键词"
									placeholderStyle="color:#BBBBBB;line-height:normal"
							/>
						</uni-forms-item>

						<uni-forms-item class="form-item" label="推送平台" name="pushPlatformCodes">
							<uni-list-item
									clickable
									@tap="state.showPushPlatform = true"
									:title="!sheep.$helper.isRealEmpty(state.model.pushPlatformCodes) ? state.model.pushPlatformNames : '请选择推送平台'"
									showArrow
									:border="false"
									class="list-border"
							></uni-list-item>
						</uni-forms-item>

						<!--TODO 暂时禁止选择套餐 默认10秒轮询-->
						<uni-forms-item class="form-item" label="订阅套餐" name="subConfigId">
							<uni-list-item
									clickable
									:title="!sheep.$helper.isRealEmpty(state.model.subConfigId) ? state.model.subConfigName : '请选择订阅套餐'"
									showArrow
									:border="false"
									class="list-border"
							></uni-list-item>
						</uni-forms-item>
					</view>

					<view class="vip-card" v-if="state.showHighConfig">
						<uni-forms-item class="form-item" label="订阅卖家" name="sellerId">
							<uni-easyinput
									v-model="state.model.taskKeyword.sellerId"
									:inputBorder="false"
									placeholder="输入商品MID, 右侧查询卖家👉"
									placeholderStyle="color:#BBBBBB;line-height:normal"
							>
								<template #right>
									<button class="generic-btn" style="width: 100rpx; height: 50rpx; font-size: 24rpx;" @tap="onSelectSellerInfo">查 询</button>
								</template>
							</uni-easyinput>
						</uni-forms-item>

						<uni-forms-item class="form-item" label="屏蔽词条" name="keyword">
							<uni-easyinput
									v-model="state.model.taskKeyword.excludeKeyword"
									:inputBorder="false"
									placeholder="输入屏蔽词，用空格分隔
									含这些词的商品将被过滤不推送!"
									placeholderStyle="color:#BBBBBB;line-height:normal"
									type="textarea"
									autoHeight
							/>
						</uni-forms-item>

						<view class="ss-flex">
							<uni-forms-item class="form-item" label="价格区间" name="minPrice">
								<uni-easyinput
										v-model="state.model.taskKeyword.minPrice"
										type="number"
										:inputBorder="false"
										placeholder="最低价格"
										placeholderStyle="color:#BBBBBB;line-height:normal"
								>
								</uni-easyinput>

							</uni-forms-item>

							<uni-forms-item class="form-item" label="至" name="maxPrice">
								<uni-easyinput
										v-model="state.model.taskKeyword.maxPrice"
										:inputBorder="false"
										type="number"
										placeholder="最高价格"
										placeholderStyle="color:#BBBBBB;line-height:normal"
								>
									<template #right>
										日元
									</template>
								</uni-easyinput>

							</uni-forms-item>
						</view>

						<uni-forms-item
								name="region"
								label="商品分类"
								@tap="state.showRegion = true"
								class="form-item"
						>
							<uni-list-item
									clickable
									:title="sheep.$helper.isRealEmpty(state.model.region) ? '请选择商品分类' : state.model.region"
									showArrow
									:border="false"
									class="list-border"
							></uni-list-item>
						</uni-forms-item>

					</view>

				</scroll-view>

			</view>
		</uni-forms>

		<!-- 底部 -->
		<su-fixed bottom :val="10" placeholder :isInset="false">
			<view class="ss-flex">
				<button style="width: 40%; background-color: #F39800 !important;" class="generic-btn" @tap="showHighConfig">
					<text class="btn-text">✨高级配置</text>
				</button>
				<!--新建任务-->
				<button style="width: 40%;" v-if="sheep.$helper.isRealEmpty(state.model.id)" class="generic-btn" @tap="onAddTask">
					<text class="btn-text">🍕立即创建</text>
				</button>
				<button style="width: 40%;" v-else class="generic-btn" @tap="onUpdateTask">
					<text class="btn-text">🍕更新配置</text>
				</button>
			</view>
		</su-fixed>

		<!-- 省市区弹窗 -->
		<su-category-picker
				:show="state.showRegion"
				@cancel="state.showRegion = false"
				@confirm="onRegionConfirm"
				:valArr = "state.model.fullArea"
		>
		</su-category-picker>

		<!--推送平台弹窗-->
		<su-popup :show="state.showPushPlatform" round="10" @close="onClosePushPlatform()">
			<view class="ss-modal-box bg-white ss-flex-col">
				<view v-if="!sheep.$helper.isRealEmpty(state.model.pushPlatformCodes)" class="text-pre label-text ss-m-b-20">推送平台：{{ state.model.pushPlatformNames }}</view>
				<view v-else class="text-pre label-text ss-m-b-20">请选择推送平台</view>
				<view class="ss-flex ss-col-center">
					<!--选择区域-->
					<scroll-view scroll-y="true" class="modal-content-scroll" @touchmove.stop>
						<view class="ss-m-b-20" v-for="platform in state.pushPlatformList" :key="platform.id">
							<view class="ss-flex ss-col-center ss-flex-wrap">
								<button
										class="ss-reset-button spec-btn"
										:class="[
                  {
                    'spec-btn-select': state.model.pushPlatformCodes === platform.code,
                  }
                ]"
										@tap="onSelectPushPlatform(platform)"
								>
									{{ pushPlatformInfo(platform) }}
								</button>
							</view>
						</view>
					</scroll-view>
				</view>
				<view class="modal-footer border-top">
					<view class="buy-box ss-flex ss-col-center ss-flex ss-col-center ss-row-center">
						<button class="ss-reset-button buy-btn ui-Shadow-Main generic-btn-more"  @tap="onConfirmPushPlatform">确 认</button>
					</view>
				</view>
			</view>
		</su-popup>

		<!--订阅套餐弹窗-->
		<su-popup :show="state.showSubConfig" round="10" @close="onCloseSubConfig()">
			<view class="ss-modal-box bg-white ss-flex-col">
				<view v-if="!sheep.$helper.isRealEmpty(state.model.subConfigId)" class="text-pre label-text ss-m-b-20">订阅套餐：{{ state.model.subConfigName }}</view>
				<view v-else class="text-pre label-text ss-m-b-20">请选择订阅套餐</view>
				<view class="ss-flex ss-col-center">
					<!--选择区域-->
					<scroll-view scroll-y="true" class="modal-content-scroll" @touchmove.stop>
						<view class="ss-m-b-20" v-for="subConfig in state.subConfigList" :key="subConfig.id">
							<view class="ss-flex ss-col-center ss-flex-wrap">
								<button
										class="ss-reset-button spec-btn"
										:class="[
                  {
                    'spec-btn-select': state.model.subConfigId == subConfig.id,
                  }
                ]"
										@tap="onSelectSubConfig(subConfig)"
								>
									{{ subConfigInfo(subConfig) }}
								</button>
							</view>
						</view>
					</scroll-view>
				</view>
				<view class="modal-footer border-top">
					<view class="buy-box ss-flex ss-col-center ss-flex ss-col-center ss-row-center">
						<button class="ss-reset-button buy-btn ui-Shadow-Main generic-btn-more"  @tap="onConfirmSubConfig">确 认</button>
					</view>
				</view>
			</view>
		</su-popup>

		<!--卖家信息弹窗-->
		<su-popup :show="state.showSellerInfo" round="10" @close="onCloseSellerInfo()">
			<view class="ss-modal-box bg-white ss-flex-col">
				<view class="text-pre label-text ss-m-b-20">
					<seller-user-card :item="state.sellerInfo" class="detail-content-selector ss-m-t-15"/>
				</view>
			</view>
			<view class="modal-footer border-top">
				<view class="buy-box ss-flex ss-col-center ss-flex ss-col-center ss-row-center">
					<button class="ss-reset-button buy-btn ui-Shadow-Main generic-btn-more"  @tap="onConfirmSellerInfo">确 认</button>
				</view>
			</view>
		</su-popup>
	</s-layout>
</template>

<script setup>
import {reactive, ref, watch} from 'vue';
import sheep from '@/sheep';
import {onLoad} from '@dcloudio/uni-app';
import _ from "lodash";

const addressFormRef = ref(null);
const state = reactive({
	model: {
		id: null,
		productId: null,
		taskKeyword: {
			keyword: null,
			sellerId: null,
			minPrice: null,
			maxPrice: null,
			excludeKeyword: null,
			categoryId: null
		},
		name: null,
		pushPlatformCodes: null,
		pushPlatformNames: null,
		subConfigId: null,
		subConfigName: null,
		fullArea: null,
		province: null,
		provinceId: null,
		cityId: null,
		districtId: null,
		city: null,
		district: null,
		region: null,
	},
	// 是否显示高级配置
	showHighConfig: false,
	showRegion: false,
	showPushPlatform: false,
	pushPlatformList: [],
	showSubConfig: false,
	subConfigList: [],
	defaultPushPlatformCode: null,
	defaultSubConfigCode: null,
	showSellerInfo: false,
	sellerInfo: null,
});

watch(
		() => state.model.province,
		(newValue) => {
			if (newValue) {
				state.model.fullArea = [state.model.provinceId,state.model.cityId,state.model.districtId]
				state.model.region = `${state.model.province}·${state.model.city}·${state.model.district}`;
			}
		},
		{
			deep: true,
		},
);
const onRegionConfirm = (e) => {
	const {city_id,city_name,district_id,district_name,province_id,province_name} = e
	state.model = {
		...state.model,
		province: province_name,
		city: city_name,
		district: district_name,
		postCode: 0,
		provinceId: province_id,
		cityId: city_id,
		districtId: district_id
	};
	state.showRegion = false;
	if (province_id !== -1) {
		console.log('选择一级分类', state.model)
		state.model.categoryId = province_id
	}
	if (city_id !== -1) {
		state.model.categoryId = city_id
		console.log('选择二级分类', state.model)
	}
	if (district_id !== -1) {
		state.model.categoryId = district_id
		console.log('选择三级分类', state.model)
	}
};
const getCategoryData = () => {
	if (_.isEmpty(uni.getStorageSync('categoryData'))) {
		sheep.$api.data.category({}).then((res) => {
			uni.setStorageSync('categoryData', res);
			console.log('已加载分类数据', uni.getStorageSync('categoryData'))
		});
	}
};


function onCloseSellerInfo() {
	state.showSellerInfo = false;
}

function onConfirmSellerInfo() {
	state.showSellerInfo = false;
	state.model.taskKeyword.sellerId = state.sellerInfo.id;
}

function onSelectSellerInfo() {
	// 解析商品ID查询卖家信息
	console.log(state.model.taskKeyword.sellerId, '-----------------> sellerId')
	if (sheep.$helper.isRealEmpty(state.model.taskKeyword.sellerId)) {
		sheep.$helper.toast('请先填写商品链接')
		return
	}
	// 链接正则表达式
	const reg = /^http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$/;
	// m开头后面跟有24179301348类似格式的11位数字则为商品ID直接跳转到商品详情
	const idReg = /^m\d+$/;
	if (reg.test(state.model.taskKeyword.sellerId)) {
		// 提取ID通过正则
		state.model.taskKeyword.sellerId = state.model.taskKeyword.sellerId.match(/m\d+/)[0];
	} else if (idReg.test(state.model.taskKeyword.sellerId)) {
		state.model.taskKeyword.sellerId = state.model.taskKeyword.sellerId
	} else {
		sheep.$helper.toast('请先填写正确的商品链接,不支持煤炉Shop')
		return
	}
	uni.$once('SELECT_SELLER', (e) => {
		console.log(e, '---------------> 选择卖家')
		state.model.taskKeyword.sellerId = e.sellerInfo.id
	});
	sheep.$helper.toast('商品拼命加载中...')
	sheep.$router.go('/pages/goods/index', { id: state.model.taskKeyword.sellerId, selectSeller: true })
}

function onClosePushPlatform() {
	state.showPushPlatform = false;
}

function onSelectPushPlatform(platform) {
	state.model.pushPlatformCodes = platform.code;
	state.model.pushPlatformNames = pushPlatformInfo(platform);
}

function onConfirmPushPlatform() {
	if (sheep.$helper.isRealEmpty(state.model.pushPlatformCodes)) {
		sheep.$helper.toast('请选择推送平台')
		return
	}
	state.showPushPlatform = false;
}

function onCloseSubConfig() {
	state.showSubConfig = false;
}

function onSelectSubConfig(subConfig) {
	state.model.subConfigId = subConfig.id;
	state.model.subConfigName = subConfigInfo(subConfig);
}

function pushPlatformInfo(platform) {
	return `${platform.name} | ${platform.desc}`
}

function subConfigInfo(subConfig) {
	let circle = subConfig.circle;
	if (circle === 0) {
		circle = '天'
	} else if (circle === 1) {
		circle = '月'
	} else if (circle === 2) {
		circle = '年'
	}
	let price = subConfig.price
	if (price === 0) {
		price = '限时免费'
	} else {
		price = `￥${price}/${circle}`
	}
	return `${subConfig.name} | ${price} | ${subConfig.queryLimit}秒内上新感知`
}

function onConfirmSubConfig() {
	if (sheep.$helper.isRealEmpty(state.model.subConfigId)) {
		sheep.$helper.toast('请选择订阅套餐')
		return
	}
	state.showSubConfig = false;
}

function onAddTask() {
	if (sheep.$helper.isRealEmpty(state.model.taskKeyword.keyword) && sheep.$helper.isRealEmpty(state.model.taskKeyword.sellerId)) {
		sheep.$helper.toast('煤炉关键词/订阅卖家至少写一个');
		return;
	}

	if (sheep.$helper.isRealEmpty(state.model.name)) {
		sheep.$helper.toast('请填写任务名称');
		return;
	}

	if (sheep.$helper.isRealEmpty(state.model.pushPlatformCodes)) {
		sheep.$helper.toast('请选择推送平台');
		return;
	}

	if (sheep.$helper.isRealEmpty(state.model.subConfigId)) {
		sheep.$helper.toast('请选择订阅套餐');
		return;
	}

	if (state.model.taskKeyword.minPrice < 0) {
		sheep.$helper.toast('最小价格不能小于0');
		return;
	}

	if (state.model.taskKeyword.minPrice > state.model.taskKeyword.maxPrice) {
		sheep.$helper.toast('最小价格不能大于最大价格');
		return;
	}

	uni.showModal({
		title: `确认添加监测任务？`,
		content: `注意绑定公众号接收消息推送！可在我的页面进行绑定设置`,
		success: async function (res) {
			if (res.confirm) {
				sheep.$api.miao.addBeta(state.model).then(res => {
					sheep.$helper.toast('添加成功');
					sheep.$router.go('/pages/index/monitorTask');
				})
			}
		}
	});
}

function showHighConfig() {
	state.showHighConfig = !state.showHighConfig
}

function onUpdateTask() {
	if (sheep.$helper.isRealEmpty(state.model.taskKeyword.keyword) && sheep.$helper.isRealEmpty(state.model.taskKeyword.sellerId)) {
		sheep.$helper.toast('煤炉关键词/订阅卖家至少写一个');
		return;
	}

	if (sheep.$helper.isRealEmpty(state.model.name)) {
		sheep.$helper.toast('请填写任务名称');
		return;
	}

	if (sheep.$helper.isRealEmpty(state.model.pushPlatformCodes)) {
		sheep.$helper.toast('请选择推送平台');
		return;
	}

	if (sheep.$helper.isRealEmpty(state.model.subConfigId)) {
		sheep.$helper.toast('请选择订阅套餐');
		return;
	}

	if (state.model.taskKeyword.minPrice < 0) {
		sheep.$helper.toast('最小价格不能小于0');
		return;
	}

	if (state.model.taskKeyword.minPrice > state.model.taskKeyword.maxPrice) {
		sheep.$helper.toast('最小价格不能大于最大价格');
		return;
	}

	sheep.$api.miao.updateBeta(state.model).then(res => {
		sheep.$helper.toast('更新成功');
		sheep.$router.go('/pages/index/monitorTask');
	})
}

async function taskInfo() {
	const infoRes = await sheep.$api.miao.taskInfo(state.model.id);
	console.log(infoRes, '--------------------> 任务详情')
	state.model = infoRes.data;
	state.model.pushPlatformNames = pushPlatformInfo(state.model.pushPlatform);
	state.model.subConfigName = subConfigInfo(state.model.subConfig);
}

onLoad(async (options) => {
	getCategoryData();
	let taskId = options.taskId;
	if (!sheep.$helper.isRealEmpty(taskId)) {
		state.model.id = taskId;
		console.log(state.model, '-------------->state.model, 编辑任务')
		await taskInfo();
	} else {
		// 读取默认的推送平台和订阅套餐
		const pRes = await sheep.$api.dict.getDict('default_push_platform', 'value');
		const sRes = await sheep.$api.dict.getDict('default_sub_config', 'value');
		console.log(pRes, sRes, '--------------> 字典配置数据')
		state.defaultPushPlatformCode = pRes.data;
		state.defaultSubConfigCode = sRes.data;
	}
	const pushRes = await sheep.$api.miao.pushPlatformList();
	console.log(pushRes, 'pushRes')
	state.pushPlatformList = pushRes.rows;
	// 默认选择推送平台
	state.pushPlatformList.forEach(item => {
		if (state.defaultPushPlatformCode === item.code) {
			state.model.pushPlatformCodes = item.code;
			state.model.pushPlatformNames = pushPlatformInfo(item);
		}
	})
	const subRes = await sheep.$api.miao.subConfigList();
	console.log(subRes, 'subRes')
	state.subConfigList = subRes.rows;
	console.log(state, '---------->state')
	// 选择默认套餐
	state.subConfigList.forEach(item => {
		if (state.defaultSubConfigCode === item.code) {
			state.model.subConfigId = item.id;
			state.model.subConfigName = subConfigInfo(item);
		}
	})
	console.log(state, '--------------> state')
});
</script>

<style lang="scss" scoped>
:deep() {
	.uni-forms-item__label .label-text {
		font-size: 28rpx !important;
		color: #333333 !important;
		line-height: normal !important;
	}

	.uni-easyinput__content-input {
		font-size: 28rpx !important;
		color: #333333 !important;
		line-height: normal !important;
		padding-left: 0 !important;
	}

	.uni-easyinput__content-textarea {
		font-size: 28rpx !important;
		color: #333333 !important;
		line-height: normal !important;
		margin-top: 8rpx !important;
	}

	.uni-icons {
		font-size: 40rpx !important;
	}

	.is-textarea-icon {
		margin-top: 22rpx;
	}

	.is-disabled {
		color: #333333;
	}
}

.default-box {
	width: 100%;
	box-sizing: border-box;
	height: 100rpx;

	.default-box-title {
		font-size: 28rpx;
		color: #333333;
		line-height: normal;
	}
}

.footer-box {
	.save-btn {
		width: 710rpx;
		height: 80rpx;
		border-radius: 40rpx;
		background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
		color: $white;
	}

	.cancel-btn {
		width: 710rpx;
		height: 80rpx;
		border-radius: 40rpx;
		background: var(--ui-BG);
	}
}

.generic-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 24rpx;
	padding: 5rpx;
	background: linear-gradient(to right, #3E3A39, #3E3A39, #3E3A39);
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
	animation: fadeInUp 0.5s ease-out both;
	color: #ffffff;
	font-weight: bold;
	font-size: 30rpx;
}

// 下单
.buy-box {
	padding: 10rpx 0;
	padding-bottom: 40rpx;

	.add-btn {
		width: 356rpx;
		height: 80rpx;
		border-radius: 40rpx 0 0 40rpx;
		background-color: var(--ui-BG-Main-light);
		color: #3E3A39;
	}

	.buy-btn {
		padding-left: 40rpx;
		padding-right: 40rpx;
		margin-bottom: 40rpx;
		height: 80rpx;
		background: linear-gradient(90deg, #3E3A39, #3E3A39);
		color: #fff;
	}
	.score-btn {
		width: 100%;
		margin: 0 20rpx;
		height: 80rpx;
		border-radius: 40rpx;
		background: linear-gradient(90deg, #3E3A39, #3E3A39);
		color: #fff;
	}
}

.ss-modal-box {
	border-radius: 30rpx 30rpx 0 0;
	max-height: 1000rpx;

	.text-pre {
		padding: 20rpx;
		margin: 30rpx;
		border-radius: 30rpx;
		color: #3E3A39;
		font-weight: bold;
		border: 2px solid #F39800;
	}

	.modal-header {
		position: relative;

	}
}

.modal-content-scroll {
	padding: 20rpx;
	margin: 30rpx;
	border-radius: 30rpx;
	color: #3E3A39;
	font-weight: bold;
	border: 2px solid #F39800;
}

.spec-btn {
	height: 60rpx;
	width: 100%;
	padding: 30rpx;
	background: #F8B62D !important;
	border-radius: 30rpx;
	color: #ffffff;
	font-size: 26rpx;
	margin-right: 20rpx;
	margin-bottom: 10rpx;
}

.spec-btn-select {
	background: #3E3A39 !important;
	border-radius: 30rpx !important;
	color: #ffffff;
}


.ui-tabbar-box {
	box-shadow: 0px -6px 10px 0px rgba(51, 51, 51, 0.2);
}
.ui-tabbar {
	display: flex;
	height: 50px;
	background: #fff;
	justify-content: flex-start;
	margin-left: 10rpx;

	.detail-tabbar-item {
		width: 100rpx;

		.item-icon {
			width: 40rpx;
			height: 40rpx;
		}

		.item-title {
			font-size: 20rpx;
			font-weight: 500;
			line-height: 20rpx;
			margin-top: 12rpx;
		}
	}
}
.btnStyle{
	border: none;
	height: fit-content;
	font-size: 12px;
	padding: 0 !important;
	color: #000000;
	margin: 0;
	background-color: transparent;
	&::after{
		border:none;
	}
}

:deep() .uni-list-item__container {
	padding-left: 0 !important;
}

.generic-btn-more {
	width: 70% !important;
	margin-top: 20rpx !important;
	border-radius: 24rpx;
	padding: 5rpx;
	animation: fadeInUp 0.5s ease-out both;
	color: #ffffff;
	font-weight: bold;
	font-size: 30rpx;
}

.base-card {
	position: relative;
	margin-top: 20rpx;
}

.base-card::before {
	content: "基础配置";
	position: absolute;
	top: -20rpx;
	left: 50%;
	transform: translateX(-50%);
	background-color: #fff;
	color: #3E3A39;
	padding: 0 20rpx;
	font-size: 28rpx;
	z-index: 10;
}

.base-card::after {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	border-top: 2px solid #3E3A39;
	z-index: 1;
}

.vip-card {
	position: relative;
	margin-top: 10rpx;
}

.vip-card::before {
	content: "高级配置";
	position: absolute;
	top: -20rpx;
	left: 50%;
	transform: translateX(-50%);
	background-color: #fff;
	color: #F39800;
	padding: 0 20rpx;
	font-size: 28rpx;
	z-index: 10;
}

.vip-card::after {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	border-top: 2px solid #F39800;
	z-index: 1;
}

</style>
